import { Button, Form, Modal } from 'antd';
import type React from 'react';
import toast from 'react-hot-toast';
import { data } from 'react-router';
import CardInfoForm from '../CardInfoForm';

interface AddCardModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const AddCardModal: React.FC<AddCardModalProps> = ({
  visible,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (values.openMoney !== undefined) {
        values.openMoney = Number.parseFloat(values.openMoney);
      }
      if (values.balance !== undefined) {
        values.balance = Number.parseFloat(values.balance);
      }
      if (values.customerID !== undefined) {
        values.customerID = Number.parseInt(values.customerID, 10);
      }
      console.log(JSON.stringify(values));
      const response = await fetch('http://localhost:8000/cards/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      if (response.ok) {
        toast.success('银行卡添加成功');
        onSuccess();
        form.resetFields();
      } else {
        const errorData = await response.json();
        toast.error(errorData.detail || '添加失败');
      }
    } catch (error) {
      toast.error('表单验证失败');
    }
  };

  return (
    <Modal
      title="新增银行卡"
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleOk}>
          提交
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical">
        <CardInfoForm />
      </Form>
    </Modal>
  );
};

export default AddCardModal;
